import { resolve } from 'node:path';
import { defineConfig, loadEnv } from 'vite';
import fs from 'fs-extra';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  return {
    root: resolve(__dirname, './'),
    base: '/view/',
    publicDir: resolve(__dirname, '../view'),
    build: {
      outDir: resolve(__dirname, '../view'),
      emptyOutDir: true,
      rollupOptions: {
        input: resolve(__dirname, '../vite/index.html'),
        output: {
          paths: resolve(__dirname, '../view'),
          entryFileNames: 'bundle.[hash].js',
          assetFileNames: '[name].[hash][extname]',
        },
      },
    },
    plugins: [
      // 拷贝 page.nj 模板文件到目标路径
      {
        name: 'copy-template-after-build',
        closeBundle: async () => {
          const src = resolve(__dirname, '../view/index.html');
          const dest = resolve(__dirname, '../view/page.nj');
          try {
            await fs.copy(src, dest);
            console.log(`✅ Copied: ${src} → ${dest}`);
          } catch (err) {
            console.error('❌ Copy failed:', err);
          }
        },
      },
    ],
  };
});
